package com.ucap.wsbs.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.CustomServiceApi;
import com.ucap.spyxmp.data.RestResultBuilder;
import com.ucap.spyxmp.model.SpyxmpApplyItem;
import com.ucap.spyxmp.model.SpyxmpYpjyxkz;
import com.ucap.spyxmp.util.CommonUtil;
import com.ucap.util.Conts;
import com.ucap.util.DateTime;
import com.ucap.util.StringUtils;
import com.ucap.weixin.model.WxWsbsUser;
import com.ucap.wsbs.model.*;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;

/**
 * Created by Administrator on 2018/5/1.
 */
public class IndexController extends Controller {
    public String retPath;

    public void getNoticeData(){

        renderJson(RestResultBuilder.builder().success().data(this.convertNoticeData()).build());
    }

    public void toNotice() {
        JSONArray dataList = this.convertNoticeData();
        if(dataList.size() > 0){
            setAttr("data", dataList);
        }
        render("/WEB-INF/wfw/spyxmp/notice.html");
    }

    private JSONArray convertNoticeData(){

        List<SpyxmpApplyItem> applyItems = SpyxmpApplyItem.me.findAll();
        if (applyItems.size() > 0) {
            JSONArray dataList = new JSONArray();
            for (SpyxmpApplyItem applyItem : applyItems) {

                String sblsh = applyItem.getStr("SBLSH");
                String tableName = applyItem.getStr("TABLENAME");

                StringBuilder sqlStb = new StringBuilder();
                sqlStb.append("select * from ");
                sqlStb.append(tableName);
                sqlStb.append(" where APPLYID = '");
                sqlStb.append(sblsh);
                sqlStb.append("'");
                Record data = Db.findFirst(sqlStb.toString());
                if(data != null){

                    String name;
                    if ("SPYXMP_SPJYXKZ".equals(tableName)) {
                        if(data.get("JYZMC") == null){
                            continue;
                        } else {
                            name = data.getStr("JYZMC");
                        }
                    } else {

                        if (data.get("QYMC") == null) {
                            continue;
                        } else {
                            name = data.getStr("QYMC");
                        }
                    }

                    if(!name.contains("东莞")){
                        System.out.println(applyItem.getStr("SBLSH"));
                        continue;
                    }
                    JSONObject dataJson = new JSONObject();

                    //脱敏
                    //name = CommonUtil.toConceal(name);

                    dataJson.put("name", name);
                    switch (applyItem.getStr("TYPE")) {
                        case "1":
                            dataJson.put("type", "补发");
                            break;
                        case "2":
                            dataJson.put("type", "注销");
                            break;
                        case "3":
                            dataJson.put("type", "变更");
                            break;
                        default:
                            dataJson.put("type", "续期");
                            break;
                    }

                    switch (tableName){
                        case "SPYXMP_SPJYXKZ":
                            dataJson.put("xm", "食品经营许可证");
                            break;
                        case "SPYXMP_YPJYXKZ":
                            dataJson.put("xm", "食品经营许可证");
                            break;
                        case "SPYXMP_YLQXJYXKZ":
                            dataJson.put("xm", "第二类医疗器械经营备案凭证");
                            break;
                        default:
                            dataJson.put("xm", "医疗器械经营许可证");
                            break;
                    }
                    dataJson.put("date", applyItem.getDate("MODIFYDATE"));
                    dataList.add(dataJson);
                }
            }
            return dataList;
        }
        return null;
    }

    public void toIndex2() {
        System.out.println("开始进入申报");
        WxWsbsUser wxUser = getSessionAttr("wxUser");
        System.out.println("wxUser" + wxUser);
        if (wxUser == null) {
            wxUser = WxWsbsUser.me.findByOpenId("oFzs600J7ywRvvuD5y1rCcF-NL3E");

            setSessionAttr("wxUser", wxUser);

        }
        try {
            WxWsbsUserInfo wxUserInfo = WxWsbsUserInfo.me.findByOpenId(wxUser.getStr("openid"));
            setSessionAttr("wxUserInfo", wxUserInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        render("/WEB-INF/wfw/index2.html");

    }

    public void toIndex() {
        System.out.println("开始进入申报");
        WxWsbsUser wxUser = getSessionAttr("wxUser");
        System.out.println("wxUser" + wxUser);
        if (wxUser == null) {
            wxUser = WxWsbsUser.me.findByOpenId("oFzs600J7ywRvvuD5y1rCcF-NL3E");

            setSessionAttr("wxUser", wxUser);

        }
        try {
            WxWsbsUserInfo wxUserInfo = WxWsbsUserInfo.me.findByOpenId(wxUser.getStr("openid"));
            setSessionAttr("wxUserInfo", wxUserInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        render("/WEB-INF/wfw/index.html");

    }

    public void toNavigation() {
        String step = getPara("step");
        WxWsbsUser wxUser = getSessionAttr("wxUser");
        try {
            if (wxUser == null) {
                wxUser = WxWsbsUser.me.findByOpenId("oFzs600J7ywRvvuD5y1rCcF-NL3E");

                setSessionAttr("wxUser", wxUser);

            }
            WxWsbsUserInfo wxUserInfo = WxWsbsUserInfo.me.findByOpenId(wxUser.getStr("openid"));
            setSessionAttr("wxUserInfo", wxUserInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        switch (step) {
            case "1":
                render("/WEB-INF/wfw/spyxmp/spjyxkz/bzxx.html");
                break;
            case "2":
                render("/WEB-INF/wfw/spyxmp/spjyxkz/zxxx.html");
                break;
            case "3":
                render("/WEB-INF/wfw/spyxmp/spjyxkz/bgxx.html");
                break;
            case "4":
                render("/WEB-INF/wfw/spyxmp/spjyxkz/yxxx.html");
                break;
            case "5":
                render("/WEB-INF/wfw/spyxmp/ypjyxkz/bzxx.html");
                break;
            case "6":
                render("/WEB-INF/wfw/spyxmp/ypjyxkz/zxxx.html");
                break;
            case "7":
                render("/WEB-INF/wfw/spyxmp/delylqxjybapz/bzxx.html");
                break;
            case "8":
                render("/WEB-INF/wfw/spyxmp/delylqxjybapz/zxxx.html");
                break;
            case "9":
                render("/WEB-INF/wfw/spyxmp/ylqxjyxkz/bzxx.html");
                break;
            case "10":
                render("/WEB-INF/wfw/spyxmp/ylqxjyxkz/zxxx.html");
                break;
            default:
                render("/WEB-INF/wfw/wsbs/navigation.html");
                break;
        }


    }

    public void toSignature() {
        render("/WEB-INF/wfw/util/signature.html");
    }

    public void toSuccess() {

        String sblsh = getPara("sblsh");
        if (!StringUtils.isEmpty(sblsh)) {

            SpyxmpApplyItem data = SpyxmpApplyItem.me.findBySblsh(sblsh);
            setAttr("data", data);
        }


        render("/WEB-INF/wfw/success.html");
    }

    public void querySbxx() {
        WxWsbsUser wxUser = getSessionAttr("wxUser");
        List<WxWsbsSbxx> sbxxList = WxWsbsSbxx.me.findByUserId(wxUser.getStr("id"));
        renderJson(RestResultBuilder.builder().success().data(sbxxList).build());
    }

    /**
     *
     */
    public void toBgsb() {
        String step = getPara("step");
        String sblsh = getSessionAttr(Conts.WSBS_SBLSH);
        WxWsbsSbxx sbxx = null;
        WxWsbsUser wxUser = getSessionAttr("wxUser");
        if (sblsh != null) {
            sbxx = WxWsbsSbxx.me.findBySblsh(sblsh);
        }
        if (StringUtils.isEmpty(sbxx.getStr("qyxx")) || !sbxx.getStr("qyxx").equals("1")) {
            WxWsbsQyxx qyxx = WxWsbsQyxx.me.findBySblsh(getSessionAttr("ysblsh").toString());
            setAttr("data", qyxx);
            retPath = "/WEB-INF/wfw/wsbs/bg/qyxx.html";
            setAttr("sbxx", sbxx);
            render(retPath);
        } else if (StringUtils.isEmpty(sbxx.getStr("zzxx")) || !sbxx.getStr("zzxx").equals("1")) {
            WxWsbsSbxx zzxx = WxWsbsSbxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));
            setAttr("data", zzxx);
            retPath = "/WEB-INF/wfw/wsbs/bg/zzxx.html";
            setAttr("sbxx", sbxx);
            render(retPath);
        } else if (StringUtils.isEmpty(sbxx.getStr("frxx")) || !sbxx.getStr("frxx").equals("1")) {
            WxWsbsFrxx frxx = WxWsbsFrxx.me.findBySblsh(getSessionAttr("ysblsh").toString());
            WxWsbsQyxx qyxx = WxWsbsQyxx.me.findBySblsh(getSessionAttr("ysblsh").toString());
            if (frxx == null) {
                WxWsbsUserInfo userInfo = WxWsbsUserInfo.me.findByOpenId(wxUser.get("openid").toString());
                frxx = new WxWsbsFrxx();
                frxx.set("name", userInfo.get("name"));
                frxx.set("sex", userInfo.get("sex"));
                frxx.set("nation", userInfo.get("nation"));
                // frxx.set("place",userInfo.get("id_address"));
                frxx.set("detailedplace", userInfo.get("id_address"));
                frxx.set("idtype", userInfo.get("1"));
                frxx.set("phone", userInfo.get("phone"));
                frxx.set("zjh", userInfo.get("idcard"));
            }

            if (qyxx.get("qyxz").equals("1")) {
                frxx.set("post", "负责人");
            } else {
                frxx.set("post", "法人");
            }
            setAttr("data", frxx);
            retPath = "/WEB-INF/wfw/wsbs/bg/frxx.html";
            setAttr("sbxx", sbxx);
            render(retPath);
        } else if (StringUtils.isEmpty(sbxx.getStr("sbxx")) || !sbxx.getStr("sbxx").equals("1")) {

            setAttr("data", sbxx);
            retPath = "/WEB-INF/wfw/wsbs/sb/index.html";
            setAttr("sbxx", sbxx);
            render(retPath);
        } else {
            String zsblsh = getZshlsh();
            sbxx.set("sblsh", zsblsh);
            sbxx.update();
            WxWsbsQyxx qyxx = WxWsbsQyxx.me.findBySblsh(sblsh);
            qyxx.set("sblsh", zsblsh);
            qyxx.update();
            WxWsbsFrxx frxx = WxWsbsFrxx.me.findBySblsh(sblsh);
            frxx.set("sblsh", zsblsh);
            frxx.update();
            List<WxWsbsFile> fileList = WxWsbsFile.me.findBySblsh(sblsh);
            for (WxWsbsFile file : fileList) {
                file.set("sblsh", zsblsh);
                file.update();
            }
            sbxx.set("sfrlsb", "0");
            sbxx.update();
            setSessionAttr("sblsh", zsblsh);
            if (!StringUtils.isEmpty(sbxx.getStr("sfrlsb")) && sbxx.getStr("sfrlsb").equals("0")) {
                redirect("/wfw/oauth/toAuth");
            } else {
                redirect("/wfw/toSbpz");
            }

        }

    }

    public void toSb() {
        String sblx = getPara("sblx");

        try {

            String sblsh = getSessionAttr(Conts.WSBS_SBLSH);
            WxWsbsSbxx sbxx = null;
            WxWsbsUser wxUser = getSessionAttr("wxUser");
            if (sblsh != null) {
                sbxx = WxWsbsSbxx.me.findBySblsh(sblsh);
            }
            if (sblsh == null || sbxx == null) {
                sblsh = StringUtils.getUUID();
                sbxx = new WxWsbsSbxx();
                sbxx.set("id", StringUtils.getUUID());
                setSessionAttr(Conts.WSBS_SBLSH, sblsh);
                sbxx.set("userid", wxUser.get("id").toString());
                sbxx.set("sblsh", sblsh);
                sbxx.set("sblx", sblx);
                sbxx.set("addtime", new DateTime().getTimestamp());
                sbxx.set("adduser", Conts.getSessionUser(getSession()).get("id"));
                sbxx.set("updatetime", new DateTime().getTimestamp());
                sbxx.set("updateuser", Conts.getSessionUser(getSession()).get("id"));
                sbxx.set("datastate", "I");
                sbxx.set("sblx", sblx);
                sbxx.set("qyxx", "0");
                sbxx.set("frxx", "0");
                sbxx.set("zzxx", "0");
                sbxx.set("sbxx", "0");
                sbxx.save();

            }
            setAttr("sbxx", sbxx);
            switch (sblx) {
                case "1":
                    System.out.println("*************************************************************");
                    System.out.println("**********************进入新办程序！！！**********************");
                    System.out.println("*************************************************************");
                    String step = getPara("step");

                    switch (step) {
                        case "qyxx":
                            WxWsbsQyxx qyxx = WxWsbsQyxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));
                            setAttr("data", qyxx);
                            retPath = "/WEB-INF/wfw/wsbs/sb/qyxx.html";
                            break;
                        case "frxx":
                            WxWsbsFrxx frxx = WxWsbsFrxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));
                            if (frxx == null) {
                                WxWsbsUserInfo userInfo = WxWsbsUserInfo.me.findByOpenId(wxUser.get("openid").toString());
                                frxx = new WxWsbsFrxx();
                                frxx.set("name", userInfo.get("name"));
                                frxx.set("sex", userInfo.get("sex"));
                                frxx.set("nation", userInfo.get("nation"));
                                // frxx.set("place",userInfo.get("id_address"));
                                frxx.set("detailedplace", userInfo.get("id_address"));
                                frxx.set("idtype", userInfo.get("1"));
                                frxx.set("phone", userInfo.get("phone"));
                                frxx.set("zjh", userInfo.get("idcard"));
                            }
                            qyxx = WxWsbsQyxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));
                            if (qyxx.get("qyxz").equals("1")) {
                                frxx.set("post", "负责人");
                            } else {
                                frxx.set("post", "法人");
                            }
                            setAttr("data", frxx);
                            retPath = "/WEB-INF/wfw/wsbs/sb/frxx.html";
                            break;
                        case "zzxx":
                            WxWsbsSbxx zzxx = WxWsbsSbxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));
                            setAttr("data", zzxx);
                            retPath = "/WEB-INF/wfw/wsbs/sb/zzxx.html";
                            break;
                        case "sbxx":
                            sbxx = WxWsbsSbxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));
                            setAttr("data", sbxx);
                            retPath = "/WEB-INF/wfw/wsbs/sb/index.html";
                            break;
                        default:
                            break;
                    }
                    System.out.println("*************************************************************");
                    System.out.println("**********************新办程序结束！！！**********************");
                    System.out.println("*************************************************************");

                    break;
                case "2":
                    System.out.println("*************************************************************");
                    System.out.println("**********************进入延续程序！！！**********************");
                    System.out.println("*************************************************************");
                    WxWsbsQyxx yqyxx = WxWsbsQyxx.me.findBySblsh(getPara("ysblsh"));
                    WxWsbsFrxx yfrxx = WxWsbsFrxx.me.findBySblsh(getPara("ysblsh"));
                    List<WxWsbsFile> yzzxx = WxWsbsFile.me.findBySblsh(getPara("ysblsh"));
                    WxWsbsSbxx ysbxx = WxWsbsSbxx.me.findBySblsh(getPara("ysblsh"));
                    setAttr("yqyxx", yqyxx);
                    setAttr("yfrxx", yfrxx);
                    setAttr("yzzxx", yzzxx);
                    setAttr("ysbxx", sbxx);
                    setAttr("sblx", getPara("sblx"));
                    setAttr("ysblsh", getPara("ysblsh"));
                    System.out.println("*************************************************************");
                    System.out.println("**********************延续程序结束！！！**********************");
                    System.out.println("*************************************************************");
                    retPath = "/WEB-INF/wfw/wsbs/yx/index.html";
                    break;
                case "3":
                    System.out.println("*************************************************************");
                    System.out.println("**********************进入变更程序！！！**********************");
                    System.out.println("*************************************************************");
                    setAttr("sblx", getPara("sblx"));
                    setAttr("ysblsh", getPara("ysblsh"));
                    setSessionAttr("ysblsh", getPara("ysblsh"));
                    System.out.println("*************************************************************");
                    System.out.println("**********************变更程序结束！！！**********************");
                    System.out.println("*************************************************************");
                    retPath = "/WEB-INF/wfw/wsbs/bg/index.html";
                    break;
                case "4":

                    System.out.println("*************************************************************");
                    System.out.println("**********************补证新办程序！！！**********************");
                    System.out.println("*************************************************************");
                    setAttr("sblx", getPara("sblx"));
                    setAttr("ysblsh", getPara("ysblsh"));
                    System.out.println("*************************************************************");
                    System.out.println("**********************补证程序结束！！！**********************");
                    System.out.println("*************************************************************");
                    retPath = "/WEB-INF/wfw/wsbs/bz/index.html";
                    break;
                case "5":
                    System.out.println("*************************************************************");
                    System.out.println("**********************注销新办程序！！！**********************");
                    System.out.println("*************************************************************");
                    setAttr("sblx", getPara("sblx"));
                    setAttr("ysblsh", getPara("ysblsh"));
                    System.out.println("*************************************************************");
                    System.out.println("**********************注销程序结束！！！**********************");
                    System.out.println("*************************************************************");
                    retPath = "/WEB-INF/wfw/wsbs/zx/index.html";
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        render(retPath);

    }

    public void toSbpz() {
        String sblsh = Conts.getWsbsSblsh(getSession());
        //String sblsh =getPara("sblsh");
        WxWsbsSbxx sbpz = WxWsbsSbxx.me.findBySblsh(sblsh);
        if (!StringUtils.isEmpty(sbpz.getStr("sfrlsb")) && sbpz.getStr("sfrlsb").equals("0")) {
            redirect("/wfw/oauth/toAuth");
        } else {
            WxWsbsUser wxUser = getSessionAttr("wxUser");
            WxWsbsFrxx frxx = null;
            if (sbpz.getStr("sblx").equals("1") || sbpz.getStr("sblx").equals("3")) {
                frxx = WxWsbsFrxx.me.findBySblsh(sbpz.getStr("sblsh"));
            } else {
                frxx = WxWsbsFrxx.me.findBySblsh(sbpz.getStr("ysblsh"));
            }

            String msgText = "尊敬的" + frxx.get("name") + "先生/女士，您好！您已成功申请食品经营许可证网上全流程办理，申报流水号：" + sbpz.get("sblsh") + "。办理结果我们将通过本公众号发送到您的微信上，敬请留意！详情请咨询：0769-22337223";
            ApiResult apiResult = CustomServiceApi.sendText(wxUser.get("openid").toString(), msgText);
            System.out.println("=====申报信息提示=====：" + apiResult.toString());
            WxWsbsFile sbcl = WxWsbsFile.me.findSbclBySblsh(Conts.getWsbsSblsh(getSession()));
            removeSessionAttr(Conts.WSBS_SBLSH);
            setAttr("data", sbpz);
            setAttr("sbcl", sbcl);
            removeSessionAttr(Conts.WSBS_SBLSH);
            render("/WEB-INF/wfw/main/sbpz.html");
        }
    }

    private void createUpdateFile(String imgStr, String tableName) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成jpeg图片
            String uploadPath = Conts.getSessionUser(getSession()).get("id").toString() + "/" + new DateTime().getYear() + "/" + new DateTime().getMonth() + "/" + new DateTime().getDay();
            System.out.println("生成jpeg图片" + uploadPath);
            String imgFilePath = "/files/upload/" + uploadPath + "/" + System.currentTimeMillis() + ".jpg";
            OutputStream out = new FileOutputStream(PathKit.getWebRootPath() + imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            File file = new File(PathKit.getWebRootPath() + imgFilePath);

            WxWsbsFile wsbsFile = new WxWsbsFile();
            wsbsFile.set("ID", StringUtils.getUUID());
            wsbsFile.set("SBLSH", Conts.getWsbsSblsh(getSession()));
            wsbsFile.set("USERID", Conts.getSessionUser(getSession()).get("id"));
            wsbsFile.set("FILEPATH", imgFilePath);
            wsbsFile.set("FILENAME", file.getName());
            wsbsFile.set("CONTENTTYPE", "image/jpeg");
            wsbsFile.set("TABLENAME", tableName);
            wsbsFile.set("ADDTIME", new DateTime().getTimestamp());
            wsbsFile.set("ADDUSER", Conts.getSessionUser(getSession()).get("id"));
            wsbsFile.set("UPDATETIME", new DateTime().getTimestamp());
            wsbsFile.set("UPDATEUSER", Conts.getSessionUser(getSession()).get("id"));
            wsbsFile.set("DATASTATE", "I");

            JSONObject msg = new JSONObject();

            boolean boo = wsbsFile.save();
            msg.put("success", boo);
            if (boo) {
                msg.put("msg", "上传材料成功");
            } else {

                msg.put("msg", "上传材料失败");
            }
            msg.put("data", wsbsFile);
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    public void toWwcsbList() {
        System.out.println("开始进入申报");
        WxWsbsUser wxUser = getSessionAttr("wxUser");
        try {
            List<WxWsbsSbxx> sbxxList = WxWsbsSbxx.me.findByUserId(wxUser.get("id").toString());
            setAttr("sbxxList", sbxxList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        render("/WEB-INF/wfw/sbls/wwcsb-list.html");

    }

    public void toNoSbList() {
        System.out.println("开始进入申报");
        WxWsbsUser wxUser = getSessionAttr("wxUser");
        try {


            List<WxWsbsSbxx> sbxxList = WxWsbsSbxx.me.findByUserId(wxUser.get("id").toString());
            for (WxWsbsSbxx item : sbxxList) {
                item.put("frxxInfo", WxWsbsFrxx.me.findBySblsh(item.getStr("sblsh")));
                item.put("qyxxInfo", WxWsbsQyxx.me.findBySblsh(item.getStr("sblsh")));
            }
            setAttr("sbxxList", sbxxList);
            setAttr("sblx", getPara("sblx"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        render("/WEB-INF/wfw/sbls/noSb-list.html");

    }

    public void toSbList() {
        System.out.println("开始进入申报");
        WxWsbsUser wxUser = getSessionAttr("wxUser");
        try {
            List<WxWsbsSbxx> sbxxList = WxWsbsSbxx.me.findAllByUserId(wxUser.get("id").toString());
            setAttr("sbxxList", sbxxList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        render("/WEB-INF/wfw/sbls/sbxx-list.html");

    }

    public String getZshlsh() {
        List<WxWsbsSbxx> sbxxList = WxWsbsSbxx.me.findLikeData();
        NumberFormat f = new DecimalFormat("00000");
        String zsblsh = null;
        if (sbxxList == null || sbxxList.size() == 0) {
            zsblsh = new DateTime().getDateTimeNYR() + f.format(1);
        } else {
            zsblsh = new DateTime().getDateTimeNYR() + f.format(sbxxList.size() + 1);
        }
        return zsblsh;
    }
}
